<?php

namespace app\admin\model\system;

use app\common\basic\BaseModel;

/**
 * 用户信息模型
 */
class SystemUser extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';
    protected $table = 'vk_ap_system_user';

    /**
     * 获取器
     */
    public function getBackendSettingAttr($value)
    {
        return json_decode($value ?? '', true);
    }

    /**
     * 修改器
     */
    public function setBackendSettingAttr($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 权限范围
     */
    public function scopeAuth($query, $value)
    {
        $id = $value['id'];
        $dept = $value['dept'];
        if ($id > 1) {
            $ids = SystemDept::whereRaw('FIND_IN_SET("'.$dept['id'].'", level) > 0')->column('id');
            $query->whereIn('dept_id', $ids);
        }
    }

    /**
     * 根据账号/昵称搜索
     */
    public function searchUsernameAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('username|nickname', '%'.$value.'%');
        }
    }

    public function searchNicknameAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('nickname', '%'.$value.'%');
        }
    }

    public function searchPhoneAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('phone|email', '%'.$value.'%');
        }
    }
    public function searchEmailAttr($query, $value) {
        if (!empty($value)) {
            $query->whereLike('email', '%'.$value.'%');
        }
    }
    
    /**
     * 根据岗位id进行搜索
     */
    public function searchPostIdAttr($query, $value)
    {
        $query->join(SystemUserPost::getTable().' post', 'user.id = post.user_id')->where('post.post_id', $value);
    }

    /**
     * 根据角色id进行搜索
     */
    public function searchRoleIdAttr($query, $value)
    {
        $query->whereIn('id', function ($query) use ($value) {
            $query->table(SystemUserRole::getTable())->where('role_id', $value)->field('user_id');
        });
        //$query->whereRaw('id in (SELECT user_id FROM system_user_role WHERE role_id =?)', [$value]);
    }

    /**
     * 通过中间表关联角色
     */
    public function roles()
    {
        return $this->belongsToMany(SystemRole::class, SystemUserRole::class, 'role_id', 'user_id');
    }

    /**
     * 通过中间表关联岗位
     */
    public function posts()
    {
        return $this->belongsToMany(SystemPost::class, SystemUserPost::class, 'post_id', 'user_id');
    }

    /**
     * 通过中间表关联部门
     */
    public function depts()
    {
        return $this->belongsTo(SystemDept::class, 'dept_id', 'id');
    }
}